<template>
  <el-dialog :title="dialog.title" v-model="dialog.visible" width="90%" style="height: 95%;" :fullscreen="false" append-to-body>
    <div>
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
            <el-form-item label="宿舍" prop="roomId">
              <!-- <el-input v-model="queryParams.roomId" placeholder="请输入宿舍ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
              <DormitoryTree ref="dormitoryTree" :buildingId="buildingId" @node-click="handleNodeClick" />
            </el-form-item>
            <el-form-item label="所在班级" prop="classId">
              <class-tree v-model="queryParams.classId" gradeDisabled />
              <!-- <el-input v-model="queryParams.classId" placeholder="请输入班级ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
              <!-- <el-autocomplete
                v-model="queryParams.className"
                :fetch-suggestions="searchClassInfo"
                :trigger-on-focus="false"
                placeholder="请选择班级"
                clearable
                @select="((e) => { queryParams.classId = e.id;  queryParams.className = e.className; })"
              >
                <template #default="{ item }">
                  <div class="value">{{ item.className }}</div>
                </template>
              </el-autocomplete> -->
            </el-form-item>
            <el-form-item label="学生姓名" prop="studentName">
              <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="打卡结果" prop="validatndResult">
              <el-select v-model="queryParams.validatndResult" placeholder="请选择打卡结果" clearable>
                <el-option v-for="dict in sg_validatnd_result" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="dateRangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </transition>
      <div class="status-title">
        <p>
          <span>{{ parseTime(record.attendanceDate, '{y}-{m}-{d}') }}</span>
          <span>{{ record.buildingName }}</span>
          <span><dict-tag :options="attendance_shift" :value="attendanceShiftRecord" /></span>
        </p>
        <p>
          <span>{{`正常：${record[`attendanceShift${attendanceShiftRecord}`].normalCount}` }}</span>
          <span>{{`晚打卡：${record[`attendanceShift${attendanceShiftRecord}`].exceptionCount}` }}</span>
          <span>{{`缺卡：${record[`attendanceShift${attendanceShiftRecord}`].missingCount}` }}</span>
        </p>
      </div>
      <el-card shadow="never">
        <el-table
          v-loading="loading"
          :data="attendanceDetailStatusList"
          @selection-change="handleSelectionChange"
          size="small"
          stripe
          style="height: calc(100vh - 400px)"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
          <el-table-column label="姓名" align="center" prop="studentName" />
          <el-table-column label="班级" align="center" width="120" prop="className" />
          <!-- <el-table-column label="学号" align="center" width="120" prop="studentNo" /> -->
          <!-- <el-table-column label="宿舍楼" align="center" width="120" prop="buildingName" /> -->
          <el-table-column label="宿舍楼层" align="center" prop="floorName" />
          <el-table-column label="宿舍号" align="center" prop="roomName" />
          <!-- <el-table-column label="日期" align="center" prop="attendanceDate" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.attendanceDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="打卡时间" align="center" width="140" prop="validatndTime" />
          <el-table-column label="打卡结果" align="center" width="100" prop="validatndResult">
            <template #default="scope">
              <dict-tag :options="sg_validatnd_result" :value="scope.row.validatndResult" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="关联的请假审批单" align="center" prop="roomId" width="300">
            <template #default="scope">
              <p>请假时间+请假类型+请假事由</p>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
          <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['dormitory:attendanceDetail:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['dormitory:attendanceDetail:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
        </el-table>
        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>
    </div>
  </el-dialog>
</template>

<script setup name="AttendanceDetail" lang="ts">
import {
  listAttendanceDetailStatus,
  getAttendanceDetailStatus,
  delAttendanceDetailStatus,
  addAttendanceDetailStatus,
  updateAttendanceDetailStatus
} from '@/api/dormitory/attendanceDetailStatus';
import { AttendanceDetailStatusVO, AttendanceDetailStatusQuery, AttendanceDetailStatusForm } from '@/api/dormitory/attendanceDetailStatus/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sg_validatnd_result, attendance_shift } = toRefs<any>(proxy?.useDict('sg_validatnd_result', 'attendance_shift'));

const attendanceDetailStatusList = ref<AttendanceDetailStatusVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeValidatndTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const attendanceDetailStatusFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AttendanceDetailStatusForm = {
  id: undefined,
  attendanceDetailId: undefined,
  attendanceShift: undefined,
  validatndTime: undefined,
  validatndResult: undefined,
  remark: undefined
};
const data = reactive<PageData<AttendanceDetailStatusForm, AttendanceDetailStatusQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    attendanceDetailId: undefined,
    attendanceShift: undefined,
    validatndResult: undefined,
    params: {
      validatndTime: undefined,
      createTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    attendanceDetailId: [{ required: true, message: '明细ID不能为空', trigger: 'blur' }],
    attendanceShift: [
      { required: true, message: '考勤班次：1早上出寝，2中午入寝，3中午出寝，4下午入寝，5下午出寝，6晚上入寝不能为空', trigger: 'blur' }
    ],
    validatndTime: [{ required: true, message: '打卡时间不能为空', trigger: 'blur' }],
    validatndResult: [{ required: true, message: '打卡结果不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询宿舍考勤明细状态列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeValidatndTime.value, 'ValidatndTime');
  const res = await listAttendanceDetailStatus(queryParams.value);
  attendanceDetailStatusList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeValidatndTime.value = ['', ''];
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  dormitoryTree.value?.clear();
  queryParams.value.className = undefined;
  initParams();
  handleQuery();
};

import { listClassInfo } from '@/api/office/class';

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AttendanceDetailStatusVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const dormitoryTree = ref();
/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  queryParams.value.buildingId = undefined;
  queryParams.value.floorId = undefined;
  queryParams.value.roomId = undefined;
  switch (data.type) {
    case 'T':
      break;
    case 'B':
      queryParams.value.buildingId = data.sourceId;
      break;
    case 'F':
      queryParams.value.floorId = data.sourceId;
      break;
    case 'R':
      queryParams.value.roomId = data.sourceId;
      break;
  }
};

const record = ref({});
const attendanceShiftRecord = ref();
const validatndResultRecord = ref();
const groupIdRecord = ref();
const buildingId = ref();

const initParams = () => {
  queryParams.value.attendanceDate = proxy?.parseTime(record.value?.attendanceDate, '{y}-{m}-{d}');
  queryParams.value.attendanceShift = attendanceShiftRecord.value;
  queryParams.value.validatndResult = validatndResultRecord.value;
  queryParams.value.groupId = groupIdRecord.value;
};

const handleShow = (row?: AttendanceStatsVO, attendanceShift: number, validatndResult: number, groupId: any) => {
  record.value = row;
  attendanceShiftRecord.value = attendanceShift;
  validatndResultRecord.value = validatndResult;
  groupIdRecord.value = groupId;
  buildingId.value = row?.buildingId;
  dateRangeValidatndTime.value = ['', ''];
  dateRangeCreateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  dormitoryTree.value?.clear();
  initParams();
  dialog.visible = true;
  getList();
};

const handleHide = (val: any) => {
  dialog.visible = false;
};

defineExpose({
  handleShow,
  handleHide
});

onMounted(() => {});
</script>

<style lang="scss">
.el-dialog__body {
  max-height: calc(95vh - 40px) !important;
}

.status-title {
  display: flex;
  p {
    padding-right: 30px;
  }
  span {
    display: inline-block;
    font-size: 16px;
    font-weight: bold;
    margin-right: 10px;
  }
}
</style>
